﻿using Medianamik.Core.Action;

namespace Medianamik.Core.Redirect
{
    public class RedirectUrlChangedActionHandler : IActionHandler
    {
        public void Initialize(ActionManager events)
        {
            events.AfterCreateNode += AfterSaveNode;
            events.AfterUpdateNode += AfterSaveNode;
        }

        void AfterSaveNode(ActionEventArgs<Node> arg)
        {
            if (arg.Item.NodeType.ID == MedianamikTypes.MedianamikRedirect)
            {
                var redirectNode = new RedirectNode { InnerNode = arg.Item };

                RedirectDictionary.Instance.AddSafe(redirectNode.RedirectFrom,
                    redirectNode.RedirectToNodeId, redirectNode.QueryString,
                    redirectNode.DefaultCulture, redirectNode.ResponseCode);
            }
            else if (arg.Item.NodeType.ID == MedianamikTypes.MedianamikExternalRedirect)
            {
                var redirectNode = new ExternalRedirectNode { InnerNode = arg.Item };
                ExternalRedirectDictionary.Instance.AddSafe(redirectNode);
            }
        }

        public string Description
        {
            get { return "Met à jour le dictionnaire de redirections apres l'édition ou la création d'une redirection"; }
        }
    }
}